/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.library.web_layer;

import cz.muni.fi.pa165.library.api.ReaderService;
import cz.muni.fi.pa165.library.api.ReaderTO;
import cz.muni.fi.pa165.library.api.UserService;
import cz.muni.fi.pa165.library.api.UserTO;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.request.Request;
;

/**
 *
 * @author dulinka
 */
public class AuthenticatedSession extends AuthenticatedWebSession {

    public AuthenticatedSession(Request request){
        super(request);
    }
    private boolean checkAdmin;
    private String user;
    private ReaderTO reader;

     
    @Override
    public boolean authenticate(String email, String password) {
        UserService userService = (UserService) ApplicationContextProvider.getApplicationContext().getBean("userService");
        ReaderService readerService = (ReaderService) ApplicationContextProvider.getApplicationContext().getBean("readerService");
        
        UserTO user = userService.findUserByEmail(email);
        ReaderTO reader =readerService.findReaderByEmail(email);
        if (user != null) {
            if ((user.getEmail().equals(email)) && (user.getPassword().equals(password))){
                this.checkAdmin = true;
                this.user = "Admin: " + user.getFirstName() + " " + user.getLastName();
                return true;
            }                
        }else if (reader!=null){
            if ((reader.getEmail().equals(email)) && (reader.getPassword().equals(password))){
                this.checkAdmin = false;
                this.user= "Reader: " + reader.getFirstName() + " " + reader.getSurname();
                this.reader = readerService.findReaderByEmail(email);
                return true;
            } 
        }
        this.user=null;
        return false;
    }

    @Override
    public Roles getRoles() {
        Roles roles = new Roles();
       
        if (isSignedIn())
        {
            if (checkAdmin){
                roles.add("LIBRARIAN");
            }
            roles.add("USER");
        }
        return roles;

    }
    
    /**
     * @return User
     */
    public String getUser()
    {
        return user;
    }
    
    public ReaderTO getReader(){
        return reader;
    }
    
    public Boolean getCheckAdmin(){
        return checkAdmin;
    }
}


